var config = require("./config.js"); //统一的网络请求方法


function request(params, isGetTonken) {

	var isToken = false;
	if (params.url.indexOf("/p/") == 0 || params.url.indexOf("/u/") == 0) {
		isToken = true;
	}
  uni.request({
    url:  params.baseUrl ? config.baseUrl + params.url : config.domain + params.url,
    //接口请求地址
    data: params.data,
    header: {
      'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded;charset=utf-8' : 'application/json;charset=utf-8',
      Authorization:  isToken ? uni.getStorageSync("user_token") : null,
    },
    method: params.method == undefined ? "POST" : params.method,
    dataType: 'json',
    responseType: params.responseType == undefined ? 'text' : params.responseType,
    success: function (res) {
      if (res.statusCode == 200) {
        //如果有定义了params.callBack，则调用 params.callBack(res.data)
        if (params.callBack) {
          params.callBack(res.data);
        }
      } else if (res.statusCode == 500) {
        uni.showToast({
          title: "服务器出了点小差",
          icon: "none"
        });
      } else if (res.statusCode == 401) {
		  uni.showToast({
		  	title:'登录信息已过期',
		  	icon:'none',
		  	success(res) {
		  		setTimeout(function(){
		  			uni.reLaunch({
		  				url:'/pages/login/login'
		  			})
		  			return;
		  		},1000);
		  	}
		  })
	  } else if (res.statusCode == 400) {
        uni.showToast({
          title: res.data,
          icon: "none"
        });
      } else {
        //如果有定义了params.errCallBack，则调用 params.errCallBack(res.data)
        if (params.errCallBack) {
          params.errCallBack(res);
        }
      }

    },
    fail: function (err) {
		console.log(err);
      uni.showToast({
        title: "服务器出了点小差",
        icon: "none"
      });
     
    }
  });
}


function customRequest(params){
  return new Promise((resolve, reject) => {
    uni.request({
      url: params.url,
      method: params.method || 'GET',
      data: params.data || {},
      header: {
        'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
      },
      method: params.method == undefined ? "POST" : params.method,
      dataType: 'json',
      success: res => {
        resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}

module.exports = {
  request,
  customRequest
};